﻿using Base.Entities.Enums;
using Base.ModuleBase.Dialogs.Views;
using log4net;
using log4net.Config;
using Prism.Ioc;
using Prism.Modularity;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using SignalRClientTool.Views;
using SignalRClientTool.ViewModels;
using Service.Net.Manager;
using DryIoc;
using SignalRClientTool.Models;
using System.Windows.Threading;

namespace SignalRClientTool
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        private static ILog _logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

        private const string _logConfigFile = @"Conf/LogConfig.xml";

        protected override void OnStartup(StartupEventArgs e)
        {
            XmlConfigurator.ConfigureAndWatch(new FileInfo(Path.Combine(ConfigManager.SoftDirectory, _logConfigFile)));
            base.OnStartup(e);

            AppDomain.CurrentDomain.UnhandledException += AppDomainUnhandledException;
            Current.DispatcherUnhandledException += CurrentApplication_DispatcherUnhandledException;
            Dispatcher.CurrentDispatcher.UnhandledException += CurrentDispatcher_UnhandledException;
        }

        private void CurrentDispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }

        private void CurrentApplication_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }

        private void AppDomainUnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception);
        }

        private void HandleException(Exception ex)
        {
            MessageHelper.ShowTips("未处理的异常，请查看日志");
            _logger.Error(ex);
        }

        protected override Window CreateShell()
        {
            //Resources.MergedDictionaries.Clear();
            return Container.Resolve<ClientToolWindow>();
        }

        protected override Rules CreateContainerRules()
        {
            return Rules.Default.WithConcreteTypeDynamicRegistrations(reuse: Reuse.Transient)
                                .With(Made.Of(FactoryMethod.ConstructorWithResolvableArguments))
                                .WithFuncAndLazyWithoutRegistration()
                                .WithTrackingDisposableTransients()
                                //.WithoutFastExpressionCompiler()//DryIoc 5.0以上的版本去掉了此方法
                                .WithFactorySelector(Rules.SelectLastRegisteredFactory());
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            containerRegistry.RegisterDialogWindow<DialogWindow>();
            containerRegistry.RegisterDialog<TipDialog>();
            containerRegistry.RegisterDialog<NetConfigView>();

            containerRegistry.RegisterSingleton<ClientToolWindowViewModel>();
            containerRegistry.RegisterSingleton<NetConfigViewModel>();
            containerRegistry.RegisterSingleton<INetManager, NetManager>();
            containerRegistry.RegisterSingleton<IClientToolManager, ClientToolManager>();
        }

        /* 以下几个任选一个，效果一样 */

        /////// <summary>
        /////// 07-Modules - Code
        /////// </summary>
        /////// <param name="moduleCatalog"></param>
        //protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        //{
        //    //直接
        //    moduleCatalog.AddModule<ModuleAModule>();
        //}

        ///// <summary>
        ///// 07-Modules - AppConfig
        ///// </summary>
        ///// <param name="moduleCatalog"></param>
        //protected override IModuleCatalog CreateModuleCatalog()
        //{
        //    ModuleCatalog catalog = new ModuleCatalog();
        //    catalog.AddModule(typeof(ModuleAModule));
        //    return catalog;
        //}

        /// <summary>
        /// 07-Modules - Directory 指向 ModuleA.dll地址
        /// </summary>
        /// <param name="moduleCatalog"></param>
        protected override IModuleCatalog CreateModuleCatalog()
        {
            //return new DirectoryModuleCatalog() { ModulePath = @".\Modules" };
            return new DirectoryModuleCatalog() { ModulePath = AppDomain.CurrentDomain.BaseDirectory };
        }

        /// <summary>
        /// 07-Modules - LoadManual -未调通，暂时不生效
        /// </summary>
        /// <param name="moduleCatalog"></param>
        //protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        //{       

        //    //将MedicineModule模块设置为按需加载
        //    //反射获取模块信息
        //    var moduleAType = typeof(ModuleAModule);
        //    //设置为按需加载
        //    moduleCatalog.AddModule(new ModuleInfo()
        //    {       //模块名
        //        ModuleName = moduleAType.Name,
        //        //模块类型
        //        ModuleType = moduleAType.AssemblyQualifiedName,
        //        //按需加载		初始化模式=按需
        //        InitializationMode = InitializationMode.OnDemand
        //    });
        //}

        /// <summary>
        /// 07-Modules - XMAL -未调通，暂时不生效
        /// </summary>
        //protected override IModuleCatalog CreateModuleCatalog()
        //{
        //    return new XamlModuleCatalog(new Uri("/Modules;component/ModuleCatalog.xaml", UriKind.Relative));
        //}
    }
}
